from django.shortcuts import render, get_object_or_404
from django.template.context_processors import request
from django.urls import reverse_lazy
from django.utils.http import urlencode
from django.views import View
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView, TemplateView

from main.forms import ArticleForm
from main.models import Article, Categorize
from django.contrib.auth.mixins import LoginRequiredMixin
from .forms import *


# Create your views here.
# 类视图必须使用混入类 混入类LoginRequiredMixin必须写在前方 否则不会生效。
# settings中设置过LOGIN_URL = "/user/login/"  类视图中不必再写ligin_url=reverse_lazy('/user/login')

class ArticleView(LoginRequiredMixin, ListView):
    paginate_by = 1

    # model = Article
    def get_queryset(self):
        c_id = self.request.GET.get('categorizes')
        if c_id:
            cat = get_object_or_404(Categorize, id=c_id)
            queryset = cat.article_set.all()
        else:
            queryset = Article.objects.all()
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        querydict = self.request.GET.copy()
        querydict.pop('page', None)  # 去掉旧的 page，避免重复
        context['query_suffix'] = ''
        if querydict:
            # 生成形如 "&categorizes=4&other=x" 的后缀
            context['query_suffix'] = '&' + urlencode(querydict, doseq=True)
        return context




class ArticleDetailView(LoginRequiredMixin, DetailView):
    model = Article
    template_name = 'main/article_detail.html'
    form_class = CommentForm
    success_url = reverse_lazy('main:article_detail')

    def form_valid(self, form):
        return form.save(commit=False)


